package com.guide.interceptors;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class ParamsInterceptor extends HandlerInterceptorAdapter {

//	private static final Logger errorLogger = LoggerFactory.getLogger(ParamsInterceptor.class);
	private static final Logger errorLogger = Logger.getLogger("error");
	private ObjectMapper objectMapper = new ObjectMapper();
	private static NamedThreadLocal<Long>  startTimeThreadLocal =   
			new NamedThreadLocal<Long>("ParamsInterceptor_start-end-time"); 

	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		errorLogger.error("xxxxxxxxxxxxxxxxxxxxxxxxcome on");
		startTimeThreadLocal.set(System.currentTimeMillis());
		if (!super.preHandle(request, response, handler)) {
			return false;
		}
		String pathInfo = request.getRequestURI().replaceFirst(request.getContextPath(), "");
//		startTimeThreadLocal.set(System.currentTimeMillis());
//		if (pathInfo.contains("refreshThread")){
//			parseJsonIntoAttribute(request);
//			return true;
//		}
		parseJsonIntoAttribute(request);
		
		if (pathInfo.contains("Move")) {
			return true;
		}
/*		int userId = Integer.valueOf(request.getHeader(Constants.KP_INNER_USERID));
//		errorLogger.error("xxxxxxxxxxxxxxxxxxxxxxxxuserId"+userId);
		if (userId <= 0) {
//			errorLogger.error("xxxxxxxxxxxxxxxxxxxxxxxxuserId-->"+userId);
			if (userId == 0) {
				String retAuthCode = request.getHeader("retAuthCode");
				String retAuthMsg = request.getHeader("retAuthMsg");
				if (!StringUtils.isEmpty(retAuthMsg)) {
					Map<String, Object> retAuthMsgMap = objectMapper.readValue(retAuthMsg, Map.class);
					request.setAttribute("retAuthCode", retAuthCode);
					request.setAttribute("retAuthMsg", retAuthMsgMap.get("msg"));
				}
				//
				throw new ServiceException(ErrorCodeEnum.SYSTEM_TOKEN_INVAILD);
			}else {//
			}
		}*/
		return true;
	}

	
	@SuppressWarnings("unchecked")
	private void parseJsonIntoAttribute(HttpServletRequest request) {
			
			Map<String,Object> attributeMap = new HashMap<String,Object>();
			
			Map parameterMap = request.getParameterMap();
			for(Object key : parameterMap.keySet()) {
				attributeMap.put((String)key,((String[])parameterMap.get(key))[0]);
			}
			
			String body = null;
		
			try {
				
				body = getRequestBody(request);				
				
//				errorLogger.error(body);
				
				if(StringUtils.isEmpty(body))
					return;
							
				Map<String, Object> params = objectMapper.readValue(body, Map.class);
			
				for (Entry<String, Object> entry: params.entrySet()) {
					attributeMap.put(entry.getKey(), entry.getValue());
				}
			
				request.setAttribute("attributeMap", attributeMap);
				
				return;
				
			} catch (Exception e) {
//				logger.debug("parseJsonIntoAttribute to Map error",e);
				//errorLogger.error("parseJsonIntoAttribute to Map error",e);
			}
			
			try {
				List<?> params = objectMapper.readValue(body, List.class);
				
				request.setAttribute("attributeMap", attributeMap);
				request.setAttribute("attributeList", params);
				return;
				
			} catch (Exception e) {
//				logger.error("parseJsonIntoAttribute to List error",e);
				//errorLogger.error("parseJsonIntoAttribute to List error",e);
//				throw new ServiceException(ErrorCode.CODE_SYS_BAD_JSONFORMAT);
			} 
			
			request.setAttribute("attributeMap", attributeMap);

		}


	private String getRequestBody(HttpServletRequest request)
			throws IOException {
		
		if (request.getContentLength() <= 0) {
			return null;
		}
		
//		errorLogger.error("contenttype:" + request.getContentType());
		
		if(StringUtils.startsWithIgnoreCase(request.getContentType(),"multipart/form-data")){
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(167772160);//写磁盘大小的范围 20M
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(167772160);//20M
			try {
				List fileItems = upload.parseRequest(request);
				Iterator iter = fileItems.iterator();
				while (iter.hasNext()) {
	                FileItem item = (FileItem) iter.next();
	                if (!item.isFormField()) {
	                	BufferedReader reader = new BufferedReader(new InputStreamReader(item.getInputStream()));
	    				return getContent(reader);
	                }
				}
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				errorLogger.error("get multipart RequestBody error",e);
			}
			return null;
		}
		else {		
		
			return getContent(request.getReader());
		}
	}


	public String getContent(BufferedReader reader) throws IOException {
		StringBuilder builder = new StringBuilder();
		String data = null;
		while((data = reader.readLine()) != null) {
			builder.append(data).append(" ");
		}
		
		reader.close();
		errorLogger.error("parseJsonInto----content----"+builder.toString());
		return builder.toString();
	}
	
}
